package com.wsh.crawler.utils;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 工具：下载网络图片 → 压缩 → 保存到临时目录
 * 注意：调用方有责任在用完后 deleteIfExists(tempFile)
 */
public final class ImageProcessUtil {

    // 可按需要提到yml
    private static final int MAX_WIDTH = 1920;  // 尺寸压缩
    private static final float QUALITY = 0.82f; // 质量压缩（0~1）
    private static final String FORMAT = "jpg"; // 统一导出 jpg

    /* 临时目录：%tmp%/handle-images  (Win/Lnx 均可用) */
    private static final Path TMP_DIR =
            Paths.get(System.getProperty("java.io.tmpdir"), "handle-images");

    static {
        // 首次加载确保目录存在
        try {
            Files.createDirectories(TMP_DIR);
        } catch (IOException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    private ImageProcessUtil() {
    }

    /**
     * 下载并压缩，返回临时文件路径（扩展名固定为 .jpg）
     */
    public static Path downloadAndCompress(String imageUrl) throws IOException {

        HttpURLConnection conn = (HttpURLConnection) new URL(imageUrl).openConnection();
        conn.setConnectTimeout(8000);
        conn.setReadTimeout(8000);

        try (InputStream in = conn.getInputStream()) {

            BufferedImage src = ImageIO.read(in);
            if (src == null) {
                throw new IOException("Unsupported image format: " + imageUrl);
            }

            int w = src.getWidth(), h = src.getHeight();
            if (w > MAX_WIDTH) {
                h = (int) (h * (MAX_WIDTH / (double) w));
                w = MAX_WIDTH;
            }

            // 文件名：img_时间戳.jpg
            String fileName = "img_" + System.currentTimeMillis() + "." + FORMAT;
            Path tempFile = TMP_DIR.resolve(fileName);

            // 压缩输出到临时文件
            try (OutputStream out = Files.newOutputStream(tempFile,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
                Thumbnails.of(src)
                        .size(w, h)
                        .outputFormat(FORMAT)
                        .outputQuality(QUALITY)
                        .toOutputStream(out);
            }
            return tempFile;
        } finally {
            conn.disconnect();
        }
    }

    /**
     * 安全删除，不抛异常
     */
    public static void deleteQuietly(Path path) {
        if (path != null) {
            try {
                Files.deleteIfExists(path);
            } catch (IOException ignored) {
            }
        }
    }
}